﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyVoteMVC.Data;
using MyVoteMVC.Domain;
using MyVoteMVC.Common;
using MyVoteMVC.Common.Objects;
using MyVoteMVC.Data.Repositories;

namespace MyVoteMVC.Service
{
    public class VoteItemService : IItemService
    {
        private const string EmailAddress = "@gzdi.com";//接收方邮箱    
        IUnitOfWork unitOfWork;
        IRepository<VT_Items> itemsRepository;
        IRepository<VT_Activities> activitiesRepository;
        IRepository<VT_Questions> questionsRepository;
   
        public VoteItemService()
        {
            unitOfWork = Factory.GetInstance<IUnitOfWork>();
            itemsRepository = unitOfWork.GetRepository<VT_Items>();
            activitiesRepository = unitOfWork.GetRepository<VT_Activities>();
            questionsRepository = unitOfWork.GetRepository<VT_Questions>();
        }


        public bool CreateItems(List<VT_Items> v_Items, string CreateBy)
        {
            foreach (VT_Items v_Item in v_Items)
            {
                if (CreateItems(v_Item.Question_ID, v_Item.Project_ID, v_Item.Item_Title, v_Item.Item_Content, (int)v_Item.Item_IfDefault, CreateBy,v_Item.ItemImage.Item_Image) == false)
                    return false;
            }
            return true;
        }


        //创建
        public bool CreateItems(string questionID, string projectID,string itemTitle, string itemContent, int IfDefault, string userEmailName, byte[] itemImage)
        {
            //判断是否有冲突
            if (!string.IsNullOrEmpty(projectID))
            {     
                VT_Questions v_Questions = questionsRepository.GetMany(o => o.Question_ID == questionID).FirstOrDefault();
                if (v_Questions != null)
                {
                    string strActivityID = v_Questions.Activity_ID.ToString();
                    int i = (from vItems in itemsRepository.QueryableEntity()
                             join vQuestions in questionsRepository.QueryableEntity() on vItems.Question_ID equals vQuestions.Question_ID
                             where vQuestions.Activity_ID==strActivityID && (vItems.Project_ID == null || vItems.Project_ID == string.Empty)
                             select vItems).Count();             
                    if (i > 0)
                    {
                        throw new ArgumentException("选项存在异常,请统一是否关联项目");
                    }
                }
            }
            else
            {
                VT_Questions v_Questions = questionsRepository.GetMany(o => o.Question_ID == questionID).FirstOrDefault();
                if (v_Questions != null)
                {
                    string strActivityID = v_Questions.Activity_ID.ToString();
                    int i = (from vItems in itemsRepository.QueryableEntity()
                             join vQuestions in questionsRepository.QueryableEntity() on vItems.Question_ID equals vQuestions.Question_ID
                             where vQuestions.Activity_ID == strActivityID && (vItems.Project_ID != null || vItems.Project_ID != string.Empty)
                             select vItems).Count();
                    if (i > 0)
                    {
                        throw new ArgumentException("选项存在异常,请统一是否关联项目");
                    }
                }
            }
            //userEmailName = userEmailName + EmailAddress;
            string itemID = Guid.NewGuid().ToString();
            VT_Items v_Items = new VT_Items();
            unitOfWork.BeginTransaction();
            v_Items.Question_ID = questionID;
            v_Items.Project_ID = projectID;
            v_Items.Created_By = userEmailName;
            v_Items.Created_Date = DateTime.Now;
            v_Items.Item_Content = itemContent;
            v_Items.Item_ID = itemID;

            int msx = Convert.ToInt32((from activity in itemsRepository.QueryableEntity()
                                       where activity.Question_ID == questionID
                                       select activity.Item_No).Max());
            v_Items.Item_No = msx + 1;

            v_Items.Item_Title = itemTitle;
            v_Items.Item_IfDefault = IfDefault;
            v_Items.ItemImage = new VT_ItemImage();
            v_Items.ItemImage.Item_ID = itemID;
            v_Items.ItemImage.Item_Image = itemImage;
            v_Items.View_Count = 0;
            v_Items.Online_Count = 0;
            v_Items.Offline_Count = 0;
            itemsRepository.Add(v_Items);
            unitOfWork.CommitTransaction();

            if (!string.IsNullOrEmpty(projectID))
            {
                VT_Activities v_Activites = (from activity in activitiesRepository.QueryableEntity()
                                             join questions in questionsRepository.QueryableEntity() on activity.Activity_ID equals questions.Activity_ID
                                             where questions.Question_ID == questionID
                                             select activity).FirstOrDefault();
                if (v_Activites != null)
                {
                    if (v_Activites.Activity_IfReadAll != 1)
                    {
                        unitOfWork.BeginTransaction();
                        v_Activites.Activity_IfReadAll = 1;
                        activitiesRepository.Update(v_Activites);
                        unitOfWork.CommitTransaction();
                    }
                }

            }
            return true;
        }

        //编辑
        public bool EditItems(string questionID, string projectID, string itemID, string itemTitle, string itemContent,int IfDefault,string userEmailName)
        {
            //判断是否有冲突
            if (!string.IsNullOrEmpty(projectID))
            {
                VT_Questions v_Questions = questionsRepository.GetMany(o => o.Question_ID == questionID).FirstOrDefault();
                if (v_Questions != null)
                {
                    string strActivityID = v_Questions.Activity_ID.ToString();
                    int i = (from vItems in itemsRepository.QueryableEntity()
                             join vQuestions in questionsRepository.QueryableEntity() on vItems.Question_ID equals vQuestions.Question_ID
                             where vQuestions.Activity_ID == strActivityID && (vItems.Project_ID == null || vItems.Project_ID == string.Empty)
                             select vItems).Count();
                    if (i > 0)
                    {
                        throw new ArgumentException("选项存在异常,请统一是否关联项目");
                    }
                }
            }
            else
            {
                VT_Questions v_Questions = questionsRepository.GetMany(o => o.Question_ID == questionID).FirstOrDefault();
                if (v_Questions != null)
                {
                    string strActivityID = v_Questions.Activity_ID.ToString();
                    int i = (from vItems in itemsRepository.QueryableEntity()
                             join vQuestions in questionsRepository.QueryableEntity() on vItems.Question_ID equals vQuestions.Question_ID
                             where vQuestions.Activity_ID == strActivityID && (vItems.Project_ID != null || vItems.Project_ID != string.Empty)
                             select vItems).Count();
                    if (i > 0)
                    {
                        throw new ArgumentException("选项存在异常,请统一是否关联项目");
                    }
                }
            }
            //userEmailName = userEmailName + EmailAddress;
            VT_Items v_Items = itemsRepository.GetMany(o => o.Question_ID == questionID && o.Item_ID == itemID).FirstOrDefault();
            if (v_Items != null)
            {
                unitOfWork.BeginTransaction();
                v_Items.Item_Title = itemTitle;
                v_Items.Project_ID = projectID;
                v_Items.Item_Content = itemContent;
                v_Items.Last_Update_By = userEmailName;
                v_Items.Last_Update_Date = DateTime.Now;
                v_Items.Item_IfDefault = IfDefault;
                itemsRepository.Update(v_Items);
                unitOfWork.CommitTransaction();
                return true;
            }
            return false;

        }

        //删除
        public bool DeleteItems(string questionID, string itemID)
        {
            VT_Items v_Items = itemsRepository.GetMany(o => o.Question_ID == questionID && o.Item_ID == itemID).FirstOrDefault();
            if (v_Items != null)
            {
                unitOfWork.BeginTransaction();
                itemsRepository.Delete(v_Items);
                unitOfWork.CommitTransaction();
                return true;
            }
            return false;
        }

        //投票 非离线
        public bool AddItemsCountOnline(string questionID, string itemID, int addCount)
        {
            VT_Items v_Items = itemsRepository.GetMany(o => o.Question_ID == questionID && o.Item_ID == itemID).FirstOrDefault();
            if (v_Items != null)
            {
                unitOfWork.BeginTransaction();
                v_Items.Online_Count = v_Items.Online_Count + addCount;
                itemsRepository.Update(v_Items);
                unitOfWork.CommitTransaction();
                return true;
            }
            return false;
        }

        //投票 离线
        public bool EditItemsCountOffline(string questionID, string itemID, int Count)
        {
            VT_Items v_Items = itemsRepository.GetMany(o => o.Question_ID == questionID && o.Item_ID == itemID).FirstOrDefault();
            if (v_Items != null)
            {
                unitOfWork.BeginTransaction();
                v_Items.Offline_Count = Count;
                itemsRepository.Update(v_Items);
                unitOfWork.CommitTransaction();
                return true;
            }
            return false;
 
        }

        public int GetItemsALLCount(string questionID, string itemID)
        {
            int count = 0;
            VT_Items v_Items = itemsRepository.GetMany(o => o.Question_ID == questionID && o.Item_ID == itemID).FirstOrDefault();
            if (v_Items != null)
            {
                if (v_Items.Online_Count != null) count = (int)v_Items.Online_Count;
                if (v_Items.Offline_Count != null) count = count + (int)v_Items.Offline_Count;
            }
            return count;
        }

        public int GetItemsOnlineCount(string questionID, string itemID)
        {
            int count = 0;
            VT_Items v_Items = itemsRepository.GetMany(o => o.Question_ID == questionID && o.Item_ID == itemID).FirstOrDefault();
            if (v_Items != null)
            {
                if (v_Items.Online_Count != null) count = (int)v_Items.Online_Count;
            }
            return count;
        }
        public int GetItemsOfflineCount(string questionID, string itemID)
        {
            int count = 0;
            VT_Items v_Items = itemsRepository.GetMany(o => o.Question_ID == questionID && o.Item_ID == itemID).FirstOrDefault();
            if (v_Items != null)
            {
                if (v_Items.Offline_Count != null) count = (int)v_Items.Offline_Count;
            }
            return count;
        }

        //获取投票项目信息
        public IList<VT_Items> GetItemsList(string questionID)
        {
            IList<VT_Items> v_Items = itemsRepository.GetMany(o => o.Question_ID == questionID).OrderBy(o => o.Item_Title).ToList();
            return v_Items;
        }

        //获取单个投票项目信息
        public VT_Items GetItems(string questionID, string itemID)
        {
            VT_Items v_Items = itemsRepository.GetMany(o => o.Question_ID == questionID && o.Item_ID == itemID).FirstOrDefault();
            return v_Items;
        }

        //获取上一次活动的投票的itemm项目
        public IList<VT_Items> GetLastActiviteItemms(string lastActiviteID)
        {
            var v_item = from v_items in itemsRepository.QueryableEntity()
                              join v_questions in questionsRepository.QueryableEntity() on v_items.Question_ID equals v_questions.Question_ID
                               where v_questions.Activity_ID == lastActiviteID
                               select v_items;
            IList<VT_Items> v_itemsList = v_item.OrderByDescending(o => (o.Online_Count + o.Offline_Count)).ToList();
            return v_itemsList;
        }

        ////父活动中已经投票的item的模糊查找
        public IList<VT_Items> GetLastActiviteItemms(string lastActiviteID,string keyword)
        {
            var v_item = from v_items in itemsRepository.QueryableEntity()
                         join v_questions in questionsRepository.QueryableEntity() on v_items.Question_ID equals v_questions.Question_ID
                         where v_questions.Activity_ID == lastActiviteID && (v_items.Online_Count > 0 || v_items.Offline_Count > 0) && (v_items.Item_Title.Contains(keyword) || v_items.Item_Content.Contains(keyword))
                         select v_items;
            IList<VT_Items> v_itemsList = v_item.OrderByDescending(o => (o.Online_Count + o.Offline_Count)).ToList();
            return v_itemsList;
        }


       //父活动中已经投票的item的获取
        public IList<VT_Items> GetLastActiviteVoteItemms(string lastActiviteID)
        {
            var v_item = from v_items in itemsRepository.QueryableEntity()
                         join v_questions in questionsRepository.QueryableEntity() on v_items.Question_ID equals v_questions.Question_ID
                         where v_questions.Activity_ID == lastActiviteID && (v_items.Online_Count > 0 || v_items.Offline_Count > 0)
                         select v_items;
            IList<VT_Items> v_itemsList = v_item.OrderByDescending(o => (o.Online_Count + o.Offline_Count)).ToList();
            return v_itemsList;
        }


        #region IDisposable Members
        private bool m_disposed;
        protected virtual void Dispose(bool disposing)
        {
            if (!m_disposed)
            {
                if (disposing)
                {
                    unitOfWork.Dispose();   
                }

                // Release unmanaged resources

                m_disposed = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~VoteItemService()
        {
            Dispose(false);
        }
        #endregion

        #region IItemService Members


        public VT_Items GetItems(string itemID)
        {
            return itemsRepository.GetEntityById(itemID);
        }

        public void AddItemsViewCount(string itemID)
        {
            var pItem = itemsRepository.GetEntityById(itemID);
            unitOfWork.BeginTransaction();
            pItem.View_Count += 1;
            itemsRepository.Update(pItem);
            unitOfWork.CommitTransaction();
        }

        #endregion

        #region IItemService Members


        public IList<VT_Items> GetItemsList(string questionID, string keyword)
        {
            IList<VT_Items> v_Items = itemsRepository.GetMany(o => o.Question_ID == questionID && (o.Item_Title.Contains(keyword) || o.Item_Content.Contains(keyword))).OrderBy(o => o.Item_Title).ToList();
            return v_Items;
        }

        //public List<ExcelObject.ExcelItem> GetExcelItems(string activityId)
        //{
        //    var v_item = from v_items in itemsRepository.QueryableEntity()
        //                 join v_questions in questionsRepository.QueryableEntity() on v_items.Question_ID equals v_questions.Question_ID
        //                 where v_questions.Activity_ID == activityId 
        //                 select v_items;
        //    IList<VT_Items> v_itemsList = v_item.OrderByDescending(o => (o.Online_Count + o.Offline_Count)).ToList();
        //    List<ExcelObject.ExcelItem> ExcelItemList = null;
        //    foreach (VT_Items v_Item in v_itemsList)
        //    {
        //        ExcelObject.ExcelItem excelItem = new ExcelObject.ExcelItem();
        //        excelItem.选项名称 = v_Item.Item_Title;
        //        excelItem.在线票数 =  v_Item.Online_Count.ToString();
        //        excelItem.离线票数 = v_Item.Offline_Count.ToString();
        //        int icount = (int)v_Item.Online_Count + (int)v_Item.Offline_Count;
        //        excelItem.合计票数 = icount.ToString();
        //        ExcelItemList.Add(excelItem);
        //    }
        //    return ExcelItemList;
        //}

        public List<ExcelObject.IExcelItem> GetExcelItems(string activityId)
        {
            var items = (from v_items in itemsRepository.QueryableEntity()
                         join v_questions in questionsRepository.QueryableEntity() on v_items.Question_ID equals v_questions.Question_ID
                         where v_questions.Activity_ID == activityId
                         select v_items).ToList();

            int questionNum = (from v_items in items
                                select v_items.Question_ID).Distinct().Count();
            if (questionNum == 1)
            {
                var result = (from v_items in items
                              select new ExcelObject.ExcelItem()
                              {
                                  合计票数 = (v_items.Offline_Count.Value + v_items.Online_Count.Value),
                                  离线票数 = v_items.Offline_Count.Value,
                                  选项名称 = v_items.Item_Title,
                                  在线票数 = v_items.Online_Count.Value
                              } as ExcelObject.IExcelItem).ToList();
                return result;
            }
            else if (questionNum > 1)
            {
                List<ExcelObject.IExcelItem> result = (from v_items in items
                                                       select new ExcelObject.ExcelItemEx()
                                                       {
                                                           问题名称 = v_items.Question.Question_Title,
                                                           合计票数 = (v_items.Offline_Count.Value + v_items.Online_Count.Value),
                                                           离线票数 = v_items.Offline_Count.Value,
                                                           选项名称 = v_items.Item_Title,
                                                           在线票数 = v_items.Online_Count.Value
                                                       } as ExcelObject.IExcelItem).ToList();
                return result;
            }
            else
            {
                return null;
            }
        }
        #endregion
    }
}
